import { createStore } from 'vuex'
import { login, logout, getInfo } from '../api/manager'
import { setToken, removeToken } from '../composables/auth'

// 创建一个新的 store 实例
const store = createStore({
    state () {
      return {
        // 用户信息
        user: null,
        asideCollapse: false,
        asideWidth: '250px'
      }
    },
    mutations: {
        // 记录用户信息
        SET_USERINFO(state, user) {
            state.user = user
        },

        REMOVE_USERINFO(state) {
          state.user = null
          removeToken()
        },
        // 展开或折叠左侧菜单
        TOGGLE_ASIDE(state) {
          if(state.asideCollapse) {
            state.asideCollapse = false
            state.asideWidth = '250px'
          } else {
            state.asideCollapse = true
            state.asideWidth = '64px'
          }
        }
    },
    actions: {
      login({commit}, {username, password}){
        return new Promise((resolve, reject)=>{
          login(username, password).then(res=>{
            // console.log('res.data.token', res.data.token)
            setToken(res.data.token)
            resolve(res)
          }).catch(err=>reject(err))
        })
      },
      logout({commit}) {
        return new Promise((resolve, reject)=>{
          logout({noTip: true}).finally(()=>{
            removeToken()
            commit("SET_USERINFO", null)
            resolve()
          })
        })
      },
      getAdminInfo({commit}) {
        return new Promise((resolve, reject)=>{
          getInfo().then(res=>{
            commit("SET_USERINFO", res.data)
            resolve(res)
          }).catch(err=>reject(err))
        })
      }
    }
  })

  export default store